﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Web;
using System.Web.Mvc;
using HYBYSoft.Company.Models;
using System.IO;
using System.Data.Objects.SqlClient;
using HYBYSoft.Company.WebSite.Helper;

namespace HYBYSoft.Company.WebSite.Areas.Admin.Controllers
{
    public class CategoryController : Controller
    {
        //数据库上下文
        CompanySiteEntities _db = new CompanySiteEntities();

        /// <summary>
        /// 类别管理首页
        /// </summary>
        /// <returns></returns>
        [Authentication]
        public ActionResult Index(string categoryName, int? isState)
        {
            //初始化查询条件
            string name = categoryName ?? string.Empty;
            int state = isState.HasValue ? isState.Value : 2;

            //根据查询条件获得数据
            var listCategory = from c in _db.Categories
                               where (state == 2 ? true : c.State == state) && (string.IsNullOrEmpty(name) || c.Name.Contains(name))
                               orderby c.ParentID
                               select c;

            //给ParentName赋值
            GetParentName(listCategory);

            //添加下拉框的数据源
            var listItem = CreateStateList();
            ViewBag.isState = listItem;

            return View(listCategory);
        }

        /// <summary>
        /// 定义搜索栏中 是否启用的下拉框
        /// </summary>
        /// <returns></returns>
        [NonAction]
        private static List<SelectListItem> CreateStateList()
        {
            var listItem = new List<SelectListItem>() { 
                (new SelectListItem() { Text = ConstDefinition.DDL_OPTIONS, Value = "2", Selected = true }),
                (new SelectListItem() { Text = "是", Value = "1", Selected = false }),
                (new SelectListItem() { Text = "否", Value = "0", Selected = false })
            };

            return listItem;
        }

        /// <summary>
        /// 根据条件查询类别信息
        /// </summary>
        /// <returns></returns>
        public ActionResult Search()
        {
            //查询条件初始化
            string name = Request["txtCategoryName"];
            int state = int.Parse(Request["isState"]);

            return RedirectToAction("Index", new { categoryName = name, isState = state });

        }

        /// <summary>
        /// 获取ParentName
        /// </summary>
        /// <param name="listCategorySearch">所有类别</param>
        [NonAction]
        private void GetParentName(IQueryable<Category> listCategorySearch)
        {
            //给ParentName赋值
            foreach (var item in listCategorySearch)
            {
                if (item.ParentID == 0)
                {
                    item.ParentName = "无";
                    continue;
                }
                item.ParentName = _db.Categories.FirstOrDefault(c => c.CategoryID == item.ParentID).Name;
            }
        }

        /// <summary>
        /// 类别详细信息
        /// </summary>
        /// <param name="category">类别对象</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Details(int id)
        {
            return View(_db.Categories.FirstOrDefault(c => c.CategoryID == id));
        }

        /// <summary>
        /// 创建类别Get请求
        /// </summary>
        /// <returns></returns>
        [Authentication]
        public ActionResult Create()
        {
            //调用自定义方法，获取所有parent数据
            var listItem = GetAllParent();
            listItem.SingleOrDefault(item => item.Value.Trim() == "0").Selected = true;
            ViewData["ddlParentID"] = listItem;

            return View();
        }

        /// <summary>
        /// 创建类别Post提交
        /// </summary>
        /// <param name="category">类别对象</param>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Create(Category category)
        {
            //获取页面元素的信息
            int parentId = int.Parse(Request["ddlParent"]);

            //保存图标信息
            category.Icon = SaveAsIcon();
            //设置父节点信息
            category.ParentID = parentId;

            //添加实体加入到数据库
            _db.Categories.AddObject(category);
            _db.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 编辑 类别界面Get请求
        /// </summary>
        /// <param name="id">类别id</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Edit(int id)
        {
            //调用自定义方法，获取所有parent数据
            var listItem = GetAllParent();

            //修改页面中 下拉框显示的值须与数据库数据吻合
            var category = _db.Categories.Where(c => c.CategoryID == id).FirstOrDefault();

            //获得当前类别的父类别，并将下拉框中的父类别选中
            listItem.SingleOrDefault(s => int.Parse(s.Value) == category.ParentID).Selected = true;
            //删除下拉框中的当前类别
            listItem.Remove(listItem.SingleOrDefault(s => int.Parse(s.Value) == id));

            ViewData["ddlParentID"] = listItem;

            return View(category);
        }

        /// <summary>
        /// 编辑成员post提交
        /// </summary>
        /// <returns></returns>
        [HttpPost]
        public ActionResult Edit(Category category)
        {
            //获取提交的实体
            Category originalCategory = _db.Categories.FirstOrDefault(c => c.CategoryID == category.CategoryID);

            string saveAsUrl = SaveAsIcon();
            //获取页面参数并构造实体
            originalCategory.Description = category.Description;
            originalCategory.Icon = saveAsUrl.Contains("notShow.jpg") ? originalCategory.Icon : saveAsUrl;
            originalCategory.Name = category.Name;
            originalCategory.ParentID = int.Parse(Request["ddlParent"]);
            originalCategory.State = category.State;

            //存入数据库
            _db.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 保存图标
        /// </summary>
        /// <returns>上传的路径</returns>
        [NonAction]
        private string SaveAsIcon()
        {
            string fileName = string.Empty;
            foreach (string upload in Request.Files)
            {
                string path = Server.MapPath(ConfigurationHelper.UplodeImagesPath);
                fileName = Guid.NewGuid().ToString() + Path.GetExtension(Request.Files[upload].FileName);
                if (Path.GetExtension(Request.Files[upload].FileName).Length != 0)
                {
                    Request.Files[upload].SaveAs(Path.Combine(path, fileName));
                }
                else
                {
                    fileName = "notShow.jpg";
                }
            }
            return fileName;
        }

        /// <summary>
        /// 启用和禁用操作
        /// </summary>
        /// <param name="id">类别id</param>
        /// <returns></returns>
        [Authentication]
        public ActionResult Delete(int id)
        {
            //获得需更改的实体
            var deleteCategory = _db.Categories.FirstOrDefault(cate => cate.CategoryID == id);

            //操作该实体的State
            deleteCategory.State = deleteCategory.State == 1 ? 0 : 1;

            if (deleteCategory.State == 0)
            {
                var childCategory = from c in _db.Categories
                         where c.ParentID == id
                         select c;
                foreach (var item in childCategory)
                {
                    item.State = 0;
                }
            }

            //存入数据库
            _db.SaveChanges();

            return RedirectToAction("Index");
        }

        /// <summary>
        /// 获取所有Parent的数据，做下拉框的前台显示
        /// </summary>
        [NonAction]
        public List<SelectListItem> GetAllParent()
        {
            var listItem = (from c in _db.Categories
                            where c.ParentID == 0 && c.State == 1
                            select new SelectListItem
                            {
                                Text = c.Name,
                                Value = SqlFunctions.StringConvert((double)c.CategoryID),
                                Selected = false
                            }).ToList();

            listItem.Insert(0, new SelectListItem() { Text = "一级目录", Value = "0", Selected = false });

            return listItem;
        }

        /// <summary>
        /// 检查该类别是否存在
        /// </summary>
        /// <param name="name">类别name</param>
        /// <returns></returns>
        public ActionResult CheckName(string name)
        {
            var count = (from m in _db.Categories
                         where m.Name == name && m.State != 0
                         select m).Count();
            return Json(count == 0, JsonRequestBehavior.AllowGet);
        }
    }
}
